package com.uduemc.biso.node.web.component.html;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.HtmlUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.node.core.common.sysconfig.ProductSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.SysFontConfig;
import com.uduemc.biso.node.core.common.sysconfig.productsysconfig.ProductSysListConfig;
import com.uduemc.biso.node.core.common.sysconfig.productsysconfig.ProductSysListTextConfig;
import com.uduemc.biso.node.core.common.syspojo.ProductDataList;
import com.uduemc.biso.node.core.common.udinpojo.PagingData;
import com.uduemc.biso.node.core.common.udinpojo.common.ImageConfig;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.core.entities.SPage;
import com.uduemc.biso.node.core.entities.SProduct;
import com.uduemc.biso.node.core.entities.SRepertoryQuote;
import com.uduemc.biso.node.core.entities.SSystemItemCustomLink;
import com.uduemc.biso.node.core.entities.custom.ProductDataTableForList;
import com.uduemc.biso.node.core.entities.custom.RepertoryQuote;
import com.uduemc.biso.node.core.utils.ComponentUtil;
import com.uduemc.biso.node.web.component.SiteUrlComponent;
import com.uduemc.biso.node.web.component.SpringContextUtils;
import com.uduemc.biso.node.web.component.html.common.HCPagingUdin;
import com.uduemc.biso.node.web.component.html.common.SystemListCrumbs;
import com.uduemc.biso.node.web.component.html.common.SystemListSearch;
import com.uduemc.biso.node.web.service.byfeign.SystemService;

import cn.hutool.core.util.StrUtil;

@Component
public class HSystemProductItemListUdin {

	private static String name = "system_product_item_list";

	@Autowired
	private BasicUdin basicUdin;

	@Autowired
	private SiteUrlComponent siteUrlComponent;

	@Autowired
	private SystemListCrumbs systemListCrumbs;

	@Autowired
	private SystemListSearch systemListSearch;

	@Autowired
	private HCPagingUdin hCPagingUdin;

	public StringBuilder html(ProductSysConfig productSysConfig, SPage page, SCategories category, List<ProductDataTableForList> listProductDataTableForList,
			List<SCategories> listSCategories, String keyword, int pageNum, int total, int pageSize)
			throws JsonParseException, JsonMappingException, IOException {
		if (productSysConfig == null || page == null) {
			return new StringBuilder("<!-- PLComp empty productSysConfig -->\n");
		}
		ProductSysListConfig productSysListConfig = productSysConfig.getList();
		ProductSysListTextConfig productSysListTextConfig = productSysConfig.getLtext();
		// 通过系统id 制作唯一编码
		String md5Id = DigestUtils.md5DigestAsHex(String.valueOf(page.getId()).getBytes());
		String listId = "list-" + DigestUtils.md5DigestAsHex(md5Id.getBytes());

		// 列表样式
		int listStyle = productSysListConfig.getStyle();

		// 顶部class
		String topClass = getTopClass(productSysListConfig);

		// 制作面包屑
		// crumbs
		List<SCategories> list = new ArrayList<>();
		idList(list, listSCategories, category != null ? category.getId() : null);
		// 反转链表
		Collections.reverse(list);
		String crumbs = crumbs(productSysConfig, page, list);

		// 搜索
		// search
		String search = search(productSysConfig, keyword, md5Id);

		// 分页部分
		String listHref = siteUrlComponent.getListHref(page, category, "[page]", keyword);
		PagingData pagingData = productSysConfig.getLtext().getPagingData();
		int pageTotal = (int) Math.ceil((double) total / (double) pageSize);
		// pagging
		StringBuilder pagging = hCPagingUdin.html(listHref, pageNum, pageTotal, pagingData);

		// 图片显示比例 $proportion
		String proportion = productSysListConfig.findProportion();

		// 显示结构方式
		int structure = productSysListConfig.getStructure();

		// 文字显示位置 靠左 居中 靠右 left center right
		String position = productSysListConfig.getPosition();

		// 通过列数获取样式width比例数值
		String rowWidth = productSysListConfig.rowWidth();

		// 设置显示列数
		int perRow = productSysListConfig.getPer_row();

		// productDataList 数据链表
		List<ProductDataList> dataList = getProductDataList(productSysListConfig, page, listProductDataTableForList);

		// 文本没有数据
		String noData = HtmlUtils.htmlEscape(productSysListTextConfig.getNoData());

		// 样式详情链接文本
		String details = HtmlUtils.htmlEscape(productSysListTextConfig.getDetails());

		// 图片动画class $imgScaleClass
		String imgScaleClass = imgScaleClass(productSysConfig);

		// 图片显示动画的html内容 $imgScaleHtml
		String imgScaleHtml = imgScaleHtml(productSysConfig);

		// 产品打开方式
		String productTarget = getProductTarget(productSysConfig);

		// 是否显示标题 1 显示 0 不显示 默认1
		int showTitle = productSysListConfig.getShowTitle();

		// 是否显示简介 1 显示 0 不显示 默认1
		int showInfo = productSysListConfig.getShowInfo();

		// 是否显示详情链接 1 显示 0 不显示 默认1
		int showDetailsLink = productSysListConfig.getShowDetailsLink();

		// 生成html渲染内容
		StringBuilder stringBuilder = new StringBuilder("<!-- PLComp -->\n");

		SysFontConfig titleStyle = productSysListConfig.getTitleStyle();
		SysFontConfig synopsisStyle = productSysListConfig.getSynopsisStyle();
		Map<String, Object> mapData = new HashMap<>();
		mapData.put("titleStyle", titleStyle);
		mapData.put("synopsisStyle", synopsisStyle);
		StringWriter render = basicUdin.render(name, "style", mapData);
		stringBuilder.append(render);

		mapData.put("topClass", topClass);
		mapData.put("crumbs", crumbs);
		mapData.put("search", search);

		mapData.put("listId", listId);
		mapData.put("noData", noData);
		mapData.put("details", details);
//		mapData.put("showCategory", showCategory);
//		mapData.put("showSynopsis", showSynopsis);
		// 列表配置相关
		mapData.put("structure", structure);
		mapData.put("showTitle", showTitle);
		mapData.put("showInfo", showInfo);
		mapData.put("showDetailsLink", showDetailsLink);

		mapData.put("position", position);
		mapData.put("perRow", perRow);
		mapData.put("rowWidth", rowWidth);
		mapData.put("proportion", proportion);
		mapData.put("imgScaleClass", imgScaleClass);
		mapData.put("imgScaleHtml", imgScaleHtml);
		mapData.put("productTarget", productTarget);
		// 列表数据
		mapData.put("dataList", dataList);
		mapData.put("pagging", pagging.toString());

		render = basicUdin.render(name, "default_" + listStyle, mapData);
		stringBuilder.append(render);

		return stringBuilder;
	}

	public List<ProductDataList> getProductDataList(ProductSysListConfig productSysListConfig, SPage page,
			List<ProductDataTableForList> listProductDataTableForList) {

		// 是否截断
		int truncation = productSysListConfig.getTruncation();
		final String imgTruncation = truncation == 0 ? "data-img=\"AllImgSize\"" : "";

		List<ProductDataList> dataList = new ArrayList<>();
		if (!CollectionUtils.isEmpty(listProductDataTableForList)) {
			listProductDataTableForList.forEach(item -> {
				ProductDataList dataItem = new ProductDataList();
				SProduct sproduct = item.getSproduct();
				String title = HtmlUtils.htmlEscape(sproduct.getTitle());
				String info = sproduct.getInfo() == null ? "" : HtmlUtils.htmlEscape(sproduct.getInfo());
				SystemService systemServiceImpl = SpringContextUtils.getBean("systemServiceImpl", SystemService.class);
				SSystemItemCustomLink sSystemItemCustomLink = null;
				try {
					sSystemItemCustomLink = systemServiceImpl.findOkOneByHostSiteSystemItemId(sproduct.getHostId(), sproduct.getSiteId(),
							sproduct.getSystemId(), sproduct.getId());
				} catch (IOException e) {
				}
				String href = siteUrlComponent.getProductHref(page, sproduct, sSystemItemCustomLink);
				dataItem.setTitle(title).setInfo(info).setHref(href);

				RepertoryQuote repertoryQuote = item.getImageFace();
				if (repertoryQuote == null || repertoryQuote.getHRepertory() == null) {
					String src = siteUrlComponent.getImgEmptySrc();
					String imgTag = "<img alt=\"\" title=\"\" src=\"" + src + "\" " + imgTruncation + " />";
					dataItem.setImgTag(imgTag);
				} else {
					HRepertory hRepertory = repertoryQuote.getHRepertory();
					SRepertoryQuote sRepertoryQuote = repertoryQuote.getSRepertoryQuote();
					String src = siteUrlComponent.getImgEmptySrc();
					if (hRepertory != null) {
						src = siteUrlComponent.getImgSrc(hRepertory);
					}
					String iTitle = "";
					String iAlt = "";
					if (sRepertoryQuote != null) {
						String sRepertoryQuoteConfig = sRepertoryQuote.getConfig();
						if (StringUtils.hasText(sRepertoryQuoteConfig)) {
							ImageConfig imageConfig = ComponentUtil.getConfig(sRepertoryQuoteConfig, ImageConfig.class);
							String imageConfigTitle = imageConfig.getTitle();
							if (StringUtils.hasText(imageConfigTitle)) {
								iTitle = HtmlUtils.htmlEscape(imageConfigTitle);
							}
							String imageConfigAlt = imageConfig.getAlt();
							if (StringUtils.hasText(imageConfigAlt)) {
								iAlt = HtmlUtils.htmlEscape(imageConfigAlt);
							}
						}
					}

					String imgTag = "<img alt=\"" + iAlt + "\" title=\"" + iTitle + "\" src=\"" + src + "\" " + imgTruncation + " />";
					dataItem.setImgTag(imgTag);
				}
				dataList.add(dataItem);
			});
		}
		return dataList;
	}

	/**
	 * 制作搜索栏目
	 * 
	 * @param articleSysConfig
	 * @param keyword
	 * @param id
	 * @return
	 */
	protected String search(ProductSysConfig productSysConfig, String keyword, String md5Id) {
		ProductSysListConfig productSysListConfig = productSysConfig.getList();
		int showSearch = productSysListConfig.getShowSearch();
		ProductSysListTextConfig productSysListTextConfig = productSysConfig.getLtext();
		StringBuilder stringBuilder = new StringBuilder();
		if (showSearch == 0) {
			return "";
		}
		String lanSearch = HtmlUtils.htmlEscape(productSysListTextConfig.getLanSearch());
		String lanSearchInput = HtmlUtils.htmlEscape(productSysListTextConfig.getLanSearchInput());
		String searchId = "search-" + md5Id;
		String inputId = "input-" + md5Id;
		if (StrUtil.isBlank(keyword)) {
			keyword = "";
		}

		stringBuilder = systemListSearch.render(searchId, inputId, lanSearch, lanSearchInput, keyword);
		return stringBuilder.toString();
	}

	/**
	 * 制作面包屑
	 * 
	 * @param yourCurrentLocation
	 * @param page
	 * @param list
	 * @return
	 */
	protected String crumbs(ProductSysConfig productSysConfig, SPage page, List<SCategories> list) {
		ProductSysListTextConfig ltext = productSysConfig.getLtext();
		ProductSysListConfig listProductSysListConfig = productSysConfig.getList();
		int crumbslasttext = listProductSysListConfig.getCrumbslasttext();

		String yourCurrentLocation = HtmlUtils.htmlEscape(ltext.getYourCurrentLocation());
		StringBuilder stringBuilder = systemListCrumbs.render(yourCurrentLocation, crumbslasttext, page, list);
		return stringBuilder.toString();
	}

	/**
	 * 通过左右、或者是上下结构确定顶部的class
	 * 
	 * @param productSysListConfig
	 * @return
	 */
	public static String getTopClass(ProductSysListConfig productSysListConfig) {
		int listStructure = productSysListConfig.getStructure();
		if (listStructure == 2) {
			// 左右结构的时候
			return "side_left";
		}
		return "";
	}

	/**
	 * 通过 categoryId 以及递归的方式获取 listSCategories 数据中全部的父级数据，然後加入到 list 链表中
	 * 
	 * @param list
	 * @param listSCategories
	 * @param categoryId
	 */
	protected static void idList(List<SCategories> list, List<SCategories> listSCategories, Long categoryId) {
		if (categoryId == null || categoryId.longValue() < 1) {
			return;
		}
		for (SCategories sCategories : listSCategories) {
			if (categoryId.longValue() == sCategories.getId().longValue()) {
				list.add(sCategories);
				if (sCategories.getParentId() != null && sCategories.getParentId().longValue() > 0) {
					idList(list, listSCategories, sCategories.getParentId());
				}
				break;
			}
		}
	}

	// 图片动画class $imgScaleClass
	public static String imgScaleClass(ProductSysConfig productSysConfig) {
		ProductSysListConfig productSysListConfig = productSysConfig.getList();
		int picAnimation = productSysListConfig.getPic_animation();
		switch (picAnimation) {
		case 1:
			return "prd_imgScaleBig";
		case 2:
			return "prd_imgTop";
		case 3:
			return "prd_imgbgWhite";
		case 4:
			return "prd_imgbgBlack";
		case 5:
			return "prd_imgF";
		default:
			return "";
		}
	}

	// 图片显示动画的html内容 $imgScaleHtml
	public static String imgScaleHtml(ProductSysConfig productSysConfig) {
		ProductSysListConfig productSysListConfig = productSysConfig.getList();
		int picAnimation = productSysListConfig.getPic_animation();
		switch (picAnimation) {
		case 3:
			return "<div class=\"imgbg\"></div>";
		case 4:
			return "<div class=\"imgbg\"></div>";
		default:
			return "";
		}
	}

	/**
	 * 列表页面，产品链接跳转方式
	 * 
	 * @param productSysConfig
	 * @return
	 */
	public static String getProductTarget(ProductSysConfig productSysConfig) {
		ProductSysListConfig list = productSysConfig.getList();
		String listTarget = list.getTarget();
		if (StringUtils.hasText(listTarget)) {
			return "target=\"" + listTarget + "\"";
		}
		return "";
	}

}
